<?php
namespace Common\Model;

use Think\Model;

class CommonModel extends Model
{
    protected $cacheTime = 86400;
    protected $orderBy;
    
    // 更新字段加
    public function updateCount($id, $col, $num = 1)
    {
        $id = (int) $id;
        return $this->execute(
            " update " . $this->getTableName() . " set {$col} = ({$col} + '{$num}') where " . $this->getPk() . " = '{$id}' "
        );
    }
    
    // 根据ID数组查询数据
    public function itemsByIds($ids = array())
    {
        if (empty($ids)) return array();
        $data = $this->where(array($this->getPk() => array('IN', $ids)))->select();
        $result = array();
        foreach ($data as $val) {
            $result[$val[$this->getPk()]] = $val;
        }
        return $result;
    }

    /**
     * 缓存查询记录
     * 为了防止冲突,以带前缀的表名为缓存的key
     */
    public function fetchAll($field = '*', $where = array()) {
        if (!$data = F($this->trueTableName)) {
            $result = $this->field($field);
            if (!empty($where)) {
                $result = $result->where($where);
            }
            $result = $result->order($this->orderBy ? : '')->select();
            $data = array();
            foreach ($result as $row) {
                $data[$row[$this->getPk()]] = $this->_format($row);
            }
            F($this->trueTableName, $data);
        }
        return $data;
    }
    
    // 清空所有缓存
    public function cleanCache($key = null)
    {
        if (is_null($key)) {
            F($this->trueTableName, NULL);
        } else {
            F($key, NULL);
        }
    }
    
    // 格式化数据
    public function _format($data)
    {
        return $data;
    }

    protected function _before_write(&$data) {}

    protected function _after_insert(&$data) {
        if (F($this->trueTableName))
            $this->cleanCache();
    }

    protected function _after_update(&$data) {
        if (F($this->trueTableName))
            $this->cleanCache();
    }

    protected function _after_delete(&$data) {
        if (F($this->trueTableName))
            $this->cleanCache();
    }
}
?>